package grg.learn.compose.wanandroid.ui.page.index

import android.webkit.WebView
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.SwipeRefreshState
import grg.learn.compose.foundations.list.Banner
import grg.learn.compose.wanandroid.R
import grg.learn.compose.wanandroid.data.model.IndexArticle
import grg.learn.compose.wanandroid.ui.foundations.GText
import grg.learn.compose.wanandroid.ui.theme.Theme
import grg.learn.compose.wanandroid.viewmodels.MainViewModel
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.mapNotNull

class HomePageStatus(
    val vm: MainViewModel,
    val swipeRefreshState: SwipeRefreshState = SwipeRefreshState(false)
) : ScrollableState by LazyListState() {

    var page = mutableStateOf<Int>(0)

    val articles = mutableStateListOf<IndexArticle>()

    /**
     * create by iso88591 at 2021/9/3
     * 0-> 去加载
     * 1-> 刷新
     * 2-> 加载完成
     * 3-> 正常
     */
    var _status = mutableStateOf(0)

    val _scrollStatus = LazyListState()

    @Composable
    fun StatusPoll() {
        var _status by _status
        var page by page

        //轮询
        when (_status) {
            0 -> {
                _status = 2
                page++
            }
            1 -> {
                swipeRefreshState.isRefreshing = true
            }
            2 -> {
                swipeRefreshState.isRefreshing = false
            }
            3 -> {
                swipeRefreshState.isRefreshing = false
            }
        }

        if (_status != 3) {
            LaunchedEffect(key1 = page, block = {
                vm.getIndexArticles("$page").mapNotNull { it?.datas }.collectLatest {
                    _status = 2
                    delay(200)
                    _status = 3
                    articles.addAll(it)
                }
            })
        }

    }

    fun canLoadMore(): Boolean {
        return _status.value == 3

    }

    @Composable
    fun LoadMore() {
        var _status by _status
        _status = 0
    }

}

@Composable
fun Theme.Home(
    pageStatus: HomePageStatus
) {

    val articles = pageStatus.articles

    val swipeRefreshState = pageStatus.swipeRefreshState

    pageStatus.StatusPoll()

    SwipeRefresh(
        state = swipeRefreshState,
        onRefresh = {
            swipeRefreshState.isRefreshing = false
        },
    ) {
        Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            LazyColumn(state = pageStatus._scrollStatus) {

                item {
                    _Banner(vm = pageStatus.vm)
                }

                items(articles.size) {
                    IndexArticleLine(article = articles[it])
                    if (it == articles.size - 1 && pageStatus.canLoadMore()) {
                        pageStatus.LoadMore()
                    }
                }
            }
            if (!pageStatus.canLoadMore()) {
                Box(
                    Modifier
                        .size(100.dp)
                        .background(Color.White),
                    contentAlignment = Alignment.Center
                ) {
                    GText(text = "加载中", style = TextStyle(Color.Black))
                }
            }
        }
    }

}

@Composable
private fun Theme.IndexArticleLine(
    article: IndexArticle
) {

    Box {

        Row {


            Image(
                painter = painterResource(id = R.drawable.ic_launcher_foreground),
                contentDescription = "爱心"
            )

            Column(Modifier.weight(1f, true)) {

                GText(text = article.title)
                GText(
                    text = "作者:${article.author} 分类:${article.type} 时间:${article.publishTime}",
                )

            }

            Image(
                painter = painterResource(id = R.drawable.ic_launcher_foreground),
                contentDescription = "更多",
                Modifier.size(Dp(15f))
            )


        }

    }


}

@Composable
fun _Banner(vm: MainViewModel) {

    var url by remember {
        mutableStateOf("")
    }
    LaunchedEffect(key1 = vm, block = {
        vm.getBanners().collectLatest {
            url = it[0].imagePath
        }
    })

    Image(
        painter = rememberImagePainter(data = url),
        contentDescription = "banner",
        Modifier
            .fillMaxWidth()
            .height(300.dp)
    )

}
